<template>
  <div>
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>广告
        <small v-if="item.id">编辑广告</small>
        <small v-else>新建广告</small>
      </h1>
      <ol class="breadcrumb">
        <li>
          <router-link to="/"><i class="fa fa-dashboard"></i> 总览</router-link>
        </li>
        <li>
          <router-link to="/advertisement">广告管理</router-link>
        </li>
        <li class="active" v-if="item.id">编辑广告</li>
        <li class="active" v-else>新建广告</li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content">

      <div class="box box-primary">
        <!--<div class="box-header with-border">-->
        <!--</div>-->
        <!-- /.box-header -->
        <!-- form start -->
        <div class="box-body">

          <form class="form-horizontal" @submit="onSave">
            <div class="form-group" :class="{'has-error': item.$errors.has('ad_slot_id')}">
              <label for="field-ad_slot_id" class="col-sm-2 control-label">广告位</label>
              <div class="col-sm-10">
                <!--<v-select class="form-control" id="field-ad_slot_id" style="width: 100%;"
                          placeholder="请选择广告位"
                          v-model="item.ad_slot_id" :options="[]">
                </v-select>-->
                <v-select class="form-control" id="field-ad_slot_id" style="width: 100%;"
                          data-tags="true" placeholder="广告位"
                          v-model="item.ad_slot_id" :options="ad_slot_id"  label="name">
                </v-select>
                <span class="help-block" v-if="item.$errors.has('ad_slot_id')">{{item.$errors.get('ad_slot_id')}}</span>
              </div>
            </div>
            <div class="form-group" :class="{'has-error': item.$errors.has('url')}">
              <label for="field-url" class="col-sm-2 control-label">点击链接</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="field-url" v-model="item.url">
                <span class="help-block" v-if="item.$errors.has('url')">{{item.$errors.get('url')}}</span>
              </div>
            </div>
            <div class="form-group" :class="{'has-error': item.$errors.has('image_upload_id')}">
              <label for="field-image_upload_id" class="col-sm-2 control-label">图片</label>
              <div class="col-sm-10">
                <upload-file class="form-control" id="field-image_upload_id"
                             v-model="item.image_upload_id"></upload-file>
                <span class="help-block" v-if="item.$errors.has('image_upload_id')">{{item.$errors.get('image_upload_id')}}</span>
              </div>
            </div>
            <div class="form-group" :class="{'has-error': item.$errors.has('description')}">
              <label for="field-description" class="col-sm-2 control-label">描述</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="field-description" v-model="item.description">
                <span class="help-block"
                      v-if="item.$errors.has('description')">{{item.$errors.get('description')}}</span>
              </div>
            </div>
            <div class="form-group" :class="{'has-error': item.$errors.has('start_at')}">
              <label for="field-start_at" class="col-sm-2 control-label">生效日期</label>
              <div class="col-sm-10">
                <div class="input-group date">
                  <div class="input-group-addon">
                    <i class="fa fa-calendar"></i>
                  </div>
                  <datepicker class="form-control" id="field-start_at"
                              v-model="item.start_at"></datepicker>
                </div>
                <span class="help-block" v-if="item.$errors.has('start_at')">{{item.$errors.get('start_at')}}</span>
              </div>
            </div>
            <div class="form-group" :class="{'has-error': item.$errors.has('end_at')}">
              <label for="field-end_at" class="col-sm-2 control-label">截止日期（不含）</label>
              <div class="col-sm-10">
                <div class="input-group date">
                  <div class="input-group-addon">
                    <i class="fa fa-calendar"></i>
                  </div>
                  <datepicker class="form-control" id="field-end_at"
                              v-model="item.end_at"></datepicker>
                </div>
                <span class="help-block" v-if="item.$errors.has('end_at')">{{item.$errors.get('end_at')}}</span>
              </div>
            </div>

          </form>
        </div>
        <!-- /.box-body -->

        <div class="box-footer">
          <router-link to="/advertisement" class="btn btn-lg btn-flat btn-default pull-left">返回</router-link>
          <button type="submit" form="editing-form" class="btn btn-lg btn-flat btn-primary" @click="onSave"
                  :disabled="saving">
            {{saving?"保存中...":"保存"}}
          </button>
        </div>
      </div>

    </section>
    <!-- /.content -->
  </div>
</template>

<script type="javascript">
    import {Vue} from 'resources/assets/js/commons/vuejs.js';
    import {TrimSelections} from 'resources/assets/js/commons/vuejs.js';
    import {alert} from 'resources/assets/js/components/SweetAlertDialogs';
    import ErrorsBuilder from 'resources/assets/js/commons/ErrorsBuilder.js';

    var resourceURL = "/advertisement";
    var resource = Vue.resource(resourceURL + '{/id}');
    // var resource = Vue.resource(resourceURL + '{/id}?_with=permissions,roles'); // 载入额外的关联数据(relationships)
    var vueConfig = {
        data: function () {
            var data = {
                item: {
                    "id": null,
                    "ad_slot_id": null,
                    "url": "",
                    "image_upload_id": null,
                    "description": "",
                    "start_at": null,
                    "end_at": null
                },
                saving: false,
                ad_slot_id:[],
            };
            data.item.$errors = ErrorsBuilder();
            return data;
        },
        beforeRouteEnter (to, from, next) {
            var ad_slot_id=[];
            return Vue.http.get('/advertisement/slot').then(function (result) {
                ad_slot_id = result.data.data;
                ad_slot_id.map(function (permission, k) {
                    console.log(permission);
                    ad_slot_id[k].value = permission.id;
                });
            }).then(function (result) {
                if (to.params.id) {
                    return resource.get({id: to.params.id});
                }
                else {
                    return {data: {data: null}};
                }
            }.bind(this)).then(function (result) {
                next(function (vm) {
                    vm.ad_slot_id = ad_slot_id;
                    if (result.data.data) {
                        vm.item = result.data.data;
                        vm.item.$errors = ErrorsBuilder();
                    }
                });
            }).catch(function (err) {
                next(false);
            });
        },
        methods: {
            onSave: function (event) {
                this.saving = true;
                this.item.$errors.removeAll();

                var promise = null;
                let payload = $.extend(true, {}, this.item);
                if (payload.id) {
                    promise = resource.update({id: payload.id}, payload).then(function (result) {
                        window.toastr["success"]("编辑已保存");
                        return result.data.data;
                    });
                }
                else {
                    promise = resource.save(payload).then(function (result) {
                        window.toastr["success"]("新增成功");
                        return result.data.data;
                    });
                }

                promise.then(function (data) {
                    return resource.get({id: data.id});
                }).then(function (result) {
                    this.saving = false;
                    this.item = result.data.data;
                    this.item.$errors = ErrorsBuilder();
                }.bind(this)).catch(function (err) {
                    this.saving = false;
                    if (err.status == 422) {
                        this.item.$errors.setAll(err.body);
                    }
                    else {
                        alert(err.data.message);
                    }
                }.bind(this));

                return false;
            },
        }
    };
    export default vueConfig;

</script>

<style lang="scss">

</style>
